from django.views import View
from django_redis import get_redis_connection
from django import http
from random import randint
from meiduo_mall.utils.response_code import RETCODE
from meiduo_mall.libs.captcha.captcha import captcha
import logging

from celery_tasks.sms.tasks import send_sms_code

logger = logging.getLogger('django')


#图形验证码
class ImageCodeView(View):
    def get(self, request, uuid):
        #利用SDK生成图形验证码（唯一标识字符串，图形验证内容字符串，二进制图片数据）
        name, text, image = captcha.generate_captcha()

        #创建redis连接对象
        redis_conn = get_redis_connection('verify_code')

        #将图形验证码字符串存入到redis中
        redis_conn.setex('img_%s' % uuid, 300, text)

        #将生存的好的图片响应给前端
        return http.HttpResponse(image, content_type='image/jpg')


#短信验证码
class SMSCodeView(View):
    def get(self, request, mobile):

        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code':RETCODE.THROTTLINGERR, 'errmsg':'频繁发送短信'})

        #接受参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('uuid')

        if all([image_code_client, uuid]) is False:
            return http.JsonResponse({'code':RETCODE.NECESSARYPARAMERR, 'errmsg':'缺少必要参数'})


        image_code_server = redis_conn.get('img_%s' % uuid)

        redis_conn.delete('img_%s' % uuid)
        #校验参数
        if image_code_server is None or image_code_client.lower() != image_code_server.decode().lower():
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR, 'errmsg':'图形验证码错误'})

        #提取图形验证码
        #图形验证码过期或者不存在
        #删除图形验证码，避免恶意测试图形验证码
        #对比图形验证码
        #生成短信验证码
        sms_code = '%06d' % randint(0, 999999)
        logger.info(sms_code)

        pl = redis_conn.pipeline()

        pl.setex('sms_%s' % mobile, 300, sms_code)

        pl.setex('send_flag_%s' % mobile, 60, 1)

        pl.execute()
        #发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)

        send_sms_code.delay(mobile, sms_code)
        #响应结果
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'短信发送成功'})




